﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Mapping;

namespace ZavrsniRad
{
    public class DAL
    {


        public DAL()
        {
            Configuration c = new Configuration();

            c.AddXmlFile("Mapping\\Research.hbm.xml");
            c.AddXmlFile("Mapping\\Part.hbm.xml");
      
           // c.AddAssembly("HelloNHibernate");
             //c.AddAssembly(Assembly.GetCallingAssembly());

            sessionFactory = c.BuildSessionFactory();
        }

        public static ISessionFactory sessionFactory = null;

        public ISession OpenSession()
        {
            
            return sessionFactory.OpenSession();
        }    
     



       public void CreateResearchAndSaveToDatabase()
       {
           Research  testResearch = new Research();
           testResearch.Name = "Test Harrisss";
           testResearch.Summary = "SVasta nesta";
           testResearch.AccessTime = DateTime.Now;
           testResearch.CreateTime = DateTime.Now;

           using (ISession session = OpenSession())
           {
               using (ITransaction transaction = session.BeginTransaction())
               {
                   session.Save(testResearch);
                   transaction.Commit();
               }
               //txtBox.Text += ("Saved Tobin to the database");

           }
       }



       public IList<Research> LoadResearchesFromDatabase()
       {
           using (ISession nhibernateSession = OpenSession())
           {
               IQuery query = nhibernateSession.CreateQuery(
               "from Research as res order by res.name asc");
               IList<Research> foundResearchs = query.List<Research>();

               return foundResearchs;
           }
       }



       public void UpdateResearch()
       {
           using (ISession session = OpenSession())
           {
               using (ITransaction transaction = session.BeginTransaction())
               {
                   IQuery q = session.CreateQuery("from Research where idResearch = 1");
                   Research res = q.List<Research>()[0];
                   res.Name = "Novo ime";
                   session.Flush();
                   transaction.Commit();
                 

               }
           }
       }
    }
}
